package site.huoqiang.emos.service.impl;

import cn.hutool.core.map.MapUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.huoqiang.emos.common.util.PageUtils;
import site.huoqiang.emos.exception.EmosException;
import site.huoqiang.emos.mapper.LeaveMapper;
import site.huoqiang.emos.pojo.Leave;
import site.huoqiang.emos.service.LeaveService;
import site.huoqiang.emos.task.LeaveWorkflowTask;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author: huoqiang huoqiang
 * @date: 2022-03-26
 */
@Slf4j
@Service
public class LeaveServiceImpl implements LeaveService {

    @Autowired
    private LeaveMapper leaveMapper;

    @Autowired
    private LeaveWorkflowTask leaveWorkflowTask;

    /**
     * 查询请假分页数据
     *
     * @param param
     * @return
     */
    @Override
    public PageUtils searchLeaveByPage(HashMap param) {
        ArrayList<HashMap> list = leaveMapper.searchLeaveByPage(param);
        long count = leaveMapper.searchLeaveCount(param);

        int start = (Integer) param.get("start");
        int length = (Integer) param.get("length");
        return new PageUtils(list, count, start, length);
    }

    /**
     * 查询请假记录总数
     *
     * @param param
     * @return
     */
    @Override
    public boolean searchContradiction(HashMap param) {
        long count = leaveMapper.searchContradiction(param);
        return count > 0;
    }

    /**
     * 新增请假记录
     *
     * @param leave
     * @return
     */
    @Override
    public int insert(Leave leave) {
        int rows = leaveMapper.insert(leave);
        if (rows == 1) {
            leaveWorkflowTask.startLeaveWorkflow(leave.getId(), leave.getUserId(), leave.getDays());
        } else {
            throw new EmosException("会议添加失败");
        }
        return rows;
    }

    /**
     * 删除请假记录
     *
     * @param param
     * @return
     */
    @Override
    public int deleteLeaveById(HashMap param) {
        int id = MapUtil.getInt(param, "id");
        String instanceIdById = leaveMapper.searchInstanceIdById(id);
        int rows = leaveMapper.deleteLeaveById(param);
        if (rows == 1) {
            leaveWorkflowTask.deleteLeaveWorkflow(instanceIdById, "员工请假", "删除请假申请");
        } else {
            throw new EmosException("删除请假申请失败");
        }
        return rows;
    }

    /**
     * 查询请假单
     *
     * @param param
     * @return
     */
    @Override
    public HashMap searchLeaveById(HashMap param) {
        HashMap map = leaveMapper.searchLeaveById(param);
        return map;
    }
}
